//
//  SetViewController.m
//  MoXiProject
//
//  Created by 周筱雯 on 2017/6/29.
//  Copyright © 2017年 周筱雯. All rights reserved.
//

#import "SetViewController.h"
#import "LoginRegViewModel.h"

#import "UpdateUserNameViewController.h"
#import "UpdatePwdViewController.h"
#import "UpdateSignatureViewController.h"
#import "BuyLotteryTicketViewController.h"

#import "MineViewModel.h"

@interface SetViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    UIActionSheetDelegate,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate
>
{
    NSTimer *timer;
    UIImageView * imageView;
}
@property (nonatomic,strong) UITableView * setTableview;
@property (nonatomic,strong) NSMutableArray * setArrayList;

@property (nonatomic,strong) LoginRegViewModel * loginViewModel;

@property (nonatomic,strong) MineViewModel * mineViewModel;
@end

@implementation SetViewController

-(LoginRegViewModel *) loginViewModel{
    
    if (!_loginViewModel) {
        _loginViewModel = [[LoginRegViewModel alloc] init];
    }
    return _loginViewModel;
}
-(MineViewModel *) mineViewModel {
    if (!_mineViewModel) {
        _mineViewModel = [[MineViewModel alloc] init];
    }
    return _mineViewModel;
}
-(UITableView *) setTableview{
    
    if (!_setTableview) {
        _setTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DEF_DEVICE_WIDTH, DEF_CONTENT_INTABBAR_HEIGHT - 49) style:UITableViewStylePlain];
        [_setTableview setDelegate:self];
        [_setTableview setDataSource:self];
        [_setTableview setTableHeaderView:[self headerView]];
        [_setTableview  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [MXUtility setExtraCellLineHidde:_setTableview tabHeader:YES tabFooter:NO];
        [_setTableview setBackgroundColor:[UIColor whiteColor]];
    }
    return _setTableview;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"设置"];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.setTableview];
    
    [self loginOutView];
}

//展示
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.setArrayList count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [[self.setArrayList objectAtIndex:section] count];
    
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.00000f;
    }
    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString * str = @"cell";
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];

        if (indexPath.section == 0) {
            if (indexPath.row == 2) {
                [cell setAccessoryType:UITableViewCellAccessoryNone];
                
                UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(DEF_DEVICE_WIDTH - 140, 0, 120, cell.height)];
                [label setTextColor:[UIColor lightGrayColor]];
                [label setTextAlignment:NSTextAlignmentRight];
                [label setFont:[UIFont systemFontOfSize:13]];
                [label setText:UserInfoShare.userCenterModel.userPhoneNumber];
                [cell addSubview:label];
            }
            else{
                [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            }
        }else{
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        }
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(15, cell.height - 1, DEF_DEVICE_WIDTH - 15, 1)];
        [view setBackgroundColor:DEF_COLOR_F0F0F0];
        [cell addSubview:view];
        
//        if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
//            cell.preservesSuperviewLayoutMargins = NO;
//        }
//        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//            [cell setLayoutMargins:UIEdgeInsetsZero];
//        }
    }
    
    [cell.textLabel setText:[[[self.setArrayList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"]];
    [cell.textLabel setFont:[UIFont systemFontOfSize:15.f]];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
#pragma mark - b
//    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
//        [cell setSeparatorInset:UIEdgeInsetsZero];
//    }
}
//点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            UpdateUserNameViewController * updateName = [[UpdateUserNameViewController alloc] init];
            [self.navigationController pushViewController:updateName animated:YES];
        }
        if (indexPath.row == 1) {
            UpdateSignatureViewController * updateSig = [[UpdateSignatureViewController alloc] init];
            [self.navigationController pushViewController:updateSig animated:YES];
        }
    }
    
    
//    else if (indexPath.section == 1){
//        if (indexPath.row == 0) {
//            
//            UpdatePwdViewController * updatePwd = [[UpdatePwdViewController alloc] init];
//            [self.navigationController pushViewController:updatePwd animated:YES];
//        }
//    }
//    else if(indexPath.section == 2){
//        if (indexPath.row == 0) {
//            BuyLotteryTicketViewController * buy = [[BuyLotteryTicketViewController alloc] init];
//            [self.navigationController pushViewController:buy animated:YES];
//        }
//    
//    }
    
    else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            [self clearCache];
        }
    }
    
}

-(UIView *) headerView{
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_DEVICE_WIDTH, 70)];
    [view setBackgroundColor:[UIColor whiteColor]];
    [MXUtility bottomLayerborder:view borderColor:DEF_COLOR_F0F0F0];
    [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ImgClick:)]];
    
    
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, 50, view.height - 20)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:UserInfoShare.userCenterModel.userImgPath] placeholderImage:DEF_NORMAL_DEFAULT_IMAGE];
    [view addSubview:imageView];
    
    imageView.layer.cornerRadius = imageView.width / 2;
    imageView.layer.masksToBounds = YES;
    
    UIImageView * detailImage = [[UIImageView alloc] initWithFrame:CGRectMake(DEF_DEVICE_WIDTH - (15  + 6), (view.height - 11)/2, 6, 11)];
    [detailImage setImage:[UIImage imageNamed:@"icon_jiant"]];
    [view addSubview:detailImage];
    
    UILabel * detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(DEF_DEVICE_WIDTH - (15 + 6 + 8 + 178), 10, 178, view.height - 20)];
    [detailLabel setTextAlignment:NSTextAlignmentRight];
    [detailLabel setFont:[UIFont systemFontOfSize:15.f]];
    [detailLabel setText:@"修改头像"];
    [view addSubview:detailLabel];
    
    return view;
}

-(void) ImgClick:(UITapGestureRecognizer *) gesture{
    
    UIAlertController * alertViewController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * pzAction = [UIAlertAction actionWithTitle:@"拍照上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 相机
        [self openCamera];
    }];
    
    UIAlertAction * xcAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 相册
        [self openPics];
    }];
    
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    
    [alertViewController addAction:pzAction];
    [alertViewController addAction:xcAction];
    [alertViewController addAction:cancelAction];
    
    [self presentViewController:alertViewController animated:YES completion:nil];
}

// 打开相机
- (void)openCamera {
    
    // UIImagePickerControllerCameraDeviceRear 后置摄像头 UIImagePickerControllerCameraDeviceFront 前置摄像头
    BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if (!isCamera) {
        NSLog(@"没有摄像头");
        return ;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.delegate = self;
    // 编辑模式
    imagePicker.allowsEditing = YES;
    
    [self.navigationController presentViewController:imagePicker animated:YES completion:^{}];
    
    //    [self.view.window.rootViewController  presentViewController:imagePicker animated:YES completion:^{
    //    }];
}

// 打开相册
- (void)openPics {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    // 编辑模式
    imagePicker.allowsEditing = YES;
    [self.navigationController presentViewController:imagePicker animated:YES completion:^{}];
    //    [self.view.window.rootViewController  presentViewController:imagePicker animated:YES completion:^{
    //    }];
}
// 选中照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    UIImage *image = [[UIImage alloc] init];
    
    if ([mediaType isEqualToString:@"public.image"]){
       
        image =  [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        
        NSData *data;
        
        if (UIImagePNGRepresentation(image) == nil) {
            
            data = UIImageJPEGRepresentation(image, 1);
            
        } else {
            
            data = UIImageJPEGRepresentation(image, 0.001); //压缩图片，方便上传
        }
        
        NSString *imageString = [data base64EncodedStringWithOptions:0];
        
        [self upLoadImageNetWork:imageString];
        

    }
    
}

-(void) upLoadImageNetWork:(NSString *) loadImg{

    [MXUtility showMBProgress:self.view message:@"正在上传"];
    
    [[self.mineViewModel uploadImageRequestParameter:loadImg] subscribeNext:^(id x) {
        
        if ([x[@"errorcode"] integerValue] == 0) {
            
            [MXUtility showTips:@"上传成功"];
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:x[@"result"][@"imgPath"]] placeholderImage:DEF_NORMAL_DEFAULT_IMAGE];

        }
        [MXUtility hideMBProgress:self.view];
    }error:^(NSError *error) {
        
        [MXUtility hideMBProgress:self.view];
    }];
    
}
-(void) loginOutView{
    
    CGFloat height;

    if (DEF_DEVICE_IphoneX) {
        
        height = DEF_CONTENT_INTABBAR_HEIGHT - (50 + 34);
    }
    else{
        
        height = DEF_CONTENT_INTABBAR_HEIGHT - 50;
    }
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, height, DEF_DEVICE_WIDTH, 50)];
    [view setBackgroundColor:DEF_COLOR_MAINCOLOR];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, view.width, view.height)];
    [button setTitle:@"退出登录" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [view addSubview:button];
    [self.view addSubview:view];
    
    
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否退出登录" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            
            [MXUtility showMBProgress:self.view message:LoadingText];
            
            [[self.loginViewModel LoginOutRequestParameter:UserInfoShare.userCenterModel.userID] subscribeNext:^(id x) {
                
                
                [self.navigationController popToRootViewControllerAnimated:YES];
                [MXUtility hideMBProgress:self.view];
                
            }error:^(NSError *error) {
                
                [MXUtility hideMBProgress:self.view];
            }];
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:okAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
            }];
}

-(void) clearCache{

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否清空缓存" preferredStyle:UIAlertControllerStyleAlert];
    
    
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"touch cancel");
        
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"清空" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [MXUtility showMBProgress:self.view message:@"正在清空,请稍等～"];
        timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
       
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
-(void)delayMethod{
    [MXUtility hideMBProgress:self.view];
    [MXUtility showTips:@"缓存清除成功～"];
    [timer invalidate];
}


-(NSMutableArray *) setArrayList{
    if (!_setArrayList) {
        
        _setArrayList = [[NSMutableArray alloc] initWithCapacity:0];
        
        NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"修改昵称",@"title",nil];
        NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"修改个性签名",@"title",nil];
        NSDictionary *dicphone = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"绑定的手机号",@"title",nil];
        NSArray * array1 = [NSArray arrayWithObjects: dic1,dic4,dicphone, nil];
        
//        NSDictionary * dicpwd = [NSDictionary dictionaryWithObjectsAndKeys:
//                                 @"修改密码",@"title", nil];
//        NSArray * arrayPwd = [NSArray arrayWithObjects:dicpwd, nil];
//        
//        NSDictionary *dic6 = [NSDictionary dictionaryWithObjectsAndKeys:
//                              @"购彩协议",@"title",nil];
//        NSArray * array2 = [NSArray arrayWithObjects:dic6, nil];
        
        NSDictionary *dic7 = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"清空缓存",@"title",nil];
        NSArray * array3 = [NSArray arrayWithObjects:dic7, nil];
        
        
        [_setArrayList addObject:array1];
//        [_setArrayList addObject:arrayPwd];
//        [_setArrayList addObject:array2];
        [_setArrayList addObject:array3];
    }
    return _setArrayList;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
